﻿using Microsoft.IdentityModel.Tokens;
using socialnetworkApp.Domain.Dto.InternalUse.OutPut;
using socialnetworkApp.Domain.Dto.Output;
using socialnetworkApp.Domain.IRepository;
using socialnetworkApp.Domain.IRepository.Repository;
using socialnetworkApp.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace socialnetworkApp.Domain.Manager
{
    public class AdminManager
    {

        private readonly IUserRepository _userRepository;
        private readonly IRoleRepository _roleRepository;
        private readonly IPermissionRepository _permissionRepository;
        public AdminManager(IUserRepository userRepository, IRoleRepository roleRepository, IPermissionRepository permissionRepository)
        {

            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _permissionRepository = permissionRepository;   
        }

        #region 用户管理

        public async Task<List<Users>> GetUserListSearch(Users Users)
        {

            string sql = "SELECT * FROM users u WHERE u.username LIKE @Username ";
            Users.Username = $"%{Users.Username}%";
            return await _userRepository.Select(Users, sql);

        }

        public async Task<List<Users>> GetUserList(Users Users)
        {

            string sql = "SELECT * FROM users ";
            return await _userRepository.Select(Users, sql);

        }

        /// <summary>
        /// 根据用户id查询当前的职位信息
        /// </summary>
        /// <returns></returns>
        public async Task<Users> GetUserRole(Users user  ) {
            string sql = "SELECT * FROM `users` WHERE id=@Id ";

            return await _userRepository.SelectFirst(user,sql);

        }

        public async Task<long> UpdateUserRole(Users user)
        {
            string sql = " update users u SET u.roles=@Roles \r\n  WHERE u.id=@Id";

            return await _userRepository.Update(user, sql); 
        }

        public async Task<long> DeleteUser(Guid Id) {


            string sql = "DELETE  FROM users u\r\nWHERE u.id=@Id";
            return await _userRepository.Delete(Id, sql);
        
        }
        public async Task<long> EditUser(Users users)
        {
            string sql = "update users u  set u.username='1232132' ," +
                "u.phone =@phone ,u.nickname=@nickname,u.password=@password ,u.updateTime=@UpdateTime WHERE u.id=@Id";
            return await _userRepository.Update(users, sql);

        }


        #endregion

        #region  角色管理
        public async Task<List<Role>> GetRoleListSearch(Role  role)
        {

            string sql = "SELECT * FROM role r WHERE r.roleName ";
            role.RoleName = $"%{role.RoleName}%";
            return await _roleRepository.Select(role, sql);

        }

        public async Task<List<Role>> GetRoleList(Role role)
        {
            string sql = "SELECT * FROM role  ";
          
            return await _roleRepository.Select(role, sql);

        }


        public async Task<int> AddRoleAsync(Role role)
        {
      
      
            string sql = "INSERT INTO role (id, roleName, updateTime, createTime, remark) VALUES(UUID(), @RoleName, NOW(), NOW(), @Remark)";
            return (int)await _roleRepository.Insert(role,sql); 
        }


        public async Task<long> UpdateRoleAsync(Role role) {


            string sql = "UPDATE `role` \r\nSET \r\n  `routes` = @Routes,\r\n  `buttons` = @Buttons,\r\n  `remark` = 'new_remark_data',\r\n  `updateTime` = NOW() \r\nWHERE \r\n  `id` =@Id;";

             return   await   _roleRepository.Update(role,sql);   
        }

        /// <summary>
        /// 根据权限Id获取角色信息
        /// </summary>
        /// <param name="RId"></param>
        /// <returns></returns>
        public async Task<List<Role>> GetRoleInfoById(List<string> RIds) {
            string sql = "SELECT * FROM   role r WHERE r.id=@Id ";
       
            return await _roleRepository.GetRoleInfoByIdsAsync(RIds, sql);
        
        }

        #endregion

        #region 菜单管理


        public async Task<List<Permission>> GetPermissionAsyncLisst() {

            Permission permission = new Permission();
            string sql = "SELECT * from  permission;";
        return await   _permissionRepository.Select(permission,sql);


        }


        #endregion





        #region 封装菜单权限数据处理方法
        /// <summary>
        /// 将多个List<string>  合并为一个List<string> 并且去重复
        /// </summary>
        /// <param name="lists">多个list集合</param>
        /// <returns></returns>
        public  List<string> MergeAndRemoveDuplicates(List<List<string>> lists)
        {
            return lists.SelectMany(x => x).Distinct().ToList();
        }
        /// <summary>
        /// 获取权限值并区分路由和button的权限值
        /// </summary>
        /// <param name="list">菜单权限数据集</param>
        /// <param name="roleIds">用户的多个角色Id</param>
        /// <returns></returns>
        public async Task<ReturnTwoCodeOutput> RetrieveAndDifferentiatePermissionsAsync(List<GetPermissionInfoOutput> list, List<string>? roleIds)
        {

            List<string>? RouteCode = new List<string>();
            List<string>? ButtonCode = new List<string>();
           var RouteIdsAndButtonIds= await ExtractRouteAndButtonIdsFromRolePermissionsAsync(list,roleIds);

             //根据路由id获取路由的权限code（权限值）
             RouteCode = GetPermissionCodesById(list, RouteIdsAndButtonIds.RouteIds);
            //根据buttom的id获取路由的权限code（权限值）
            ButtonCode = GetPermissionCodesById(list, RouteIdsAndButtonIds.ButtonIds);

            ReturnTwoCodeOutput returnTwoCode = new ReturnTwoCodeOutput { RouteCode = RouteCode, ButtonCode = ButtonCode };
            return returnTwoCode;
        }

        /// <summary>
        /// 将每个角色权限信息中的route Id和button 的 id拿到
        /// </summary>
        /// <param name="list">菜单权限数据集</param>
        /// <param name="roleIds">用户的多个角色Id</param>
        /// <returns></returns>
        public async Task<ReturnTwoIdOutput> ExtractRouteAndButtonIdsFromRolePermissionsAsync(List<GetPermissionInfoOutput> list, List<string>? roleIds) {

            //获取权限信息
            var roleListInfo = await GetRoleInfoById(roleIds);
            List<List<string>> Routeslists = new List<List<string>>();
            List<List<string>> Buttonslists = new List<List<string>>();
            //将每个角色权限信息中的route Id和button 的 id拿到
            foreach (var role in roleListInfo)
            {
                if (role.Routes != null)
                {
                    //拿到
                    var Routesinfo = JsonSerializer.Deserialize<List<string>>(role.Routes);
                    if (Routesinfo != null)
                    {
                        Routeslists.Add(Routesinfo);
                    }
                }

                if (role.Buttons != null)
                {
                    var Buttonsinfo = JsonSerializer.Deserialize<List<string>>(role.Buttons);
                    if (Buttonsinfo != null)
                    {
                        Buttonslists.Add(Buttonsinfo);
                    }
                }
            }
            //将每一个角色权限路由和按钮权限的的id都拿到
            var RouteIds = MergeAndRemoveDuplicates(Routeslists);
            var ButtonIds = MergeAndRemoveDuplicates(Buttonslists);

            ReturnTwoIdOutput returnTwoId = new ReturnTwoIdOutput {RouteIds= RouteIds, ButtonIds =ButtonIds };
            return returnTwoId;
        }
        /// <summary>
        /// 根据权限id获取，权限的code（权限值）
        /// </summary>
        /// <param name="list">菜单数据集</param>
        /// <param name="PermissionIds">菜单id</param>
        /// <returns>返回的是处理好的拿到code权值list</returns>
        public List<string> GetPermissionCodesById(List<GetPermissionInfoOutput> list, List<string> PermissionIds) {
            if (!PermissionIds.IsNullOrEmpty())
            {
                for (int i = 0; i < PermissionIds.Count; i++)
                {
                    // 找到与当前 ID 匹配的节点
                    GetPermissionInfoOutput node = list.Find(n => n.Id == PermissionIds[i]);

                    // 如果找到节点，递归地查找子节点中是否存在匹配的 ID，并将名称添加到结果数组中
                    if (node != null)
                    {
                        if (node.Id == PermissionIds[i])
                        {
                            PermissionIds[i] =node.Code;
                        }
                    }
                }
            }
            return PermissionIds;

        }

        /// <summary>
        /// 删除指定权限id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<long> RemovePermission(string id) {
            string sql = "DELETE FROM permission WHERE id =@id   OR pid =@id;";

            return await _permissionRepository.Delete(id,sql);
        }
        public async Task<long> SavePermission(Permission permission) {
            string sql = "INSERT INTO permission (id, code, level, name, pid) VALUES (@id,@code, @level, @name, @pid);";
            return await _permissionRepository.Insert(permission,sql);
        }

        public async Task<List<Permission>> SelectPermissionId() {

            string sql = "SELECT id FROM permission;";
            List<Permission> list = new List<Permission>();
            Permission permission = new Permission();
         list=   await _permissionRepository.Select(permission,sql);

            return list;        
        }

        #endregion
    }
}